/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
$(document).ready(function(){
    var additionalNum = 0;
    var additionalID = 0;
    init();
    //添加追加任务
    $(".additionalBtn").on("click touch",function(){
        if($(this).hasClass("additionalBtnDisabled") || $(this).hasClass("disabled")){
            return false;
        }
        var html = "<div class='additionalItem' index='"+additionalID+"'>"+$("#additionalItemTemp").html()+"</div>";
        $(".additional").append(html);
        
        //追加任务年份可叠加（需求变更）
        var optionHtml = "";
        for(var i=1;i<100;i++){
            optionHtml += "<option value='"+i+"'>第"+i+"年</option>";
        }
        $(".additional .additionalItem").last().find(".additionalStartDueTime,.additionalEndDueTime").html(optionHtml);
        /*******
        //获取目前最大的追加日期
        var additionalYear = 0;
        $(".additionalStartDueTime,.additionalEndDueTime").each(function(){
            if(!isNaN($(this).val())){
                additionalYear = $(this).val() > additionalYear ? $(this).val() : additionalYear;
            }
        });
        additionalYear++;
        //追加期间  范围
        var optionHtml = "";
        for(var i=additionalYear;i<100;i++){
            optionHtml += "<option value='"+i+"'>第"+i+"年</option>";
        }
        $(".additional .additionalItem").last().find(".additionalStartDueTime,.additionalEndDueTime").html(optionHtml).val(additionalYear);
        ******/
        additionalNum++;
        if(additionalNum >= 5){
            $(this).addClass("additionalBtnDisabled");
        }
        additionalID++;
    });
    //删除追加任务
    $(".additional").on("click touch",".deleteItem",function(){
        if($(this).hasClass("disabled")){
            return false;
        }
        additionalNum--;
        $(this).parents(".additionalItem").remove();
        $(".additionalBtn").removeClass("additionalBtnDisabled");
    });
    //更改追加时间后，初始化后面的追加时间
    $(".additional").on("change",".additionalStartDueTime,.additionalEndDueTime",function(){
        var index = $(this).parents(".additionalItem").attr("index");
        var additionalYear = parseInt($(this).val());
        //若当前是开始时间，则将结束时间重置
        if($(this).hasClass("additionalStartDueTime")){
                var optionHtml = "";
                for(var i=additionalYear;i<100;i++){
                    optionHtml += "<option value='"+i+"'>第"+i+"年</option>";
                }
                $(this).parents(".additionalItem").find(".additionalEndDueTime").html(optionHtml).val(additionalYear);
                additionalYear++;
        }
        /************
        //将当前修改的追加任务之后的任务的开始结束日期重置
        $(".additionalItem").each(function(){
            if($(this).attr("index") > index){
                var optionHtml = "";
                for(var i=additionalYear;i<100;i++){
                    optionHtml += "<option value='"+i+"'>第"+i+"年</option>";
                }
                $(this).find(".additionalStartDueTime,.additionalEndDueTime").html(optionHtml).val(additionalYear);
                additionalYear++;
            }
        });
        **********/
    });
    //利息计算类型切换
    $(".compare,.compound,.flat").on("click touch",function(){
        if($(this).hasClass("disabled")){
            return false;
        }
        $(".compare,.compound,.flat").removeClass("actived");
        $(this).addClass("actived");
        if($(this).attr("type") == '1'){
            $(".interestType .subItem").hide();
        }else{
            $(".interestType .subItem").show();
        }
    });
    //利息计算方式切换
    $(".dayType,.monthType,.yearType").on("click touch",function(){
        if($(this).hasClass("disabled")){
            return false;
        }
        $(".dayType,.monthType,.yearType").removeClass("actived");
        $(this).addClass("actived");
    });
    //计算结果  选择年份后，移动滚动条位置
    $(".currentTime").on("change",function(){
        var currentTime = parseInt($(this).val());
        var left = $(".result .scroll").offset().left + (currentTime/99)*$(".result .scroll").width() - $(".scrollBox").offset().left - $(".scrollicon").width()*1/3;
        $(".scrollicon").css({"left":left,"position":"absolute","top":"18%"});
        
        if(params.topType == '1'){
            //单利
            var flat = flatInterest(params.principal ,params.rate ,params.dueTime ,currentTime,params.additional);
        }else if(params.topType == '2'){
            //复利
            var compound = compoundInterest(params.principal ,params.rate ,params.dueTime ,currentTime ,params.subType ,params.additional);
        }else{
            //单复利对比
            var flat = flatInterest(params.principal ,params.rate ,params.dueTime ,currentTime,params.additional);
            var compound = compoundInterest(params.principal ,params.rate ,params.dueTime ,currentTime ,params.subType ,params.additional);
        }
        if(flat === false || compound === false){
            alert("计算错误，请检查输入项");
            return false;
        }
        if(params.topType == '1'){
            $(".principalTotal").html("本金和：<t>"+flat['principalTotal']+"元</t>");
            $(".interestTotal").html("利息和：<t>"+flat['interestTotal'].toFixed(2)+"元</t>");
            $(".allTotal").html("本息和：<t>"+flat['total'].toFixed(2)+"元</t>");
        }else if(params.topType == '2'){
            $(".principalTotal").html("本金和：<t>"+compound['principalTotal']+"元</t>");
            $(".interestTotal").html("利息和：<t>"+compound['interestTotal'].toFixed(2)+"元</t>");
            $(".allTotal").html("本息和：<t>"+compound['total'].toFixed(2)+"元</t>");
        }else{
            $(".principalTotal").html("本金和：<t>"+compound['principalTotal']+"元</t>");
            $(".interestTotal").html("单利本息和：<t>"+flat['total'].toFixed(2)+"元</t>");
            $(".allTotal").html("复利本息和：<t>"+compound['total'].toFixed(2)+"元</t>");
        }
        //因为详细列表固定显示99年，所以改变选择的年数，无变化
//        $(".resultList .list-item-data").remove();
//        $(".resultList").hide();
    });
    //绑定滑动滚条效果
    $(".scrollicon").on("touchstart",function(){
        var scrollWidth = $(".scroll").width();
        var scrolliconMin = $(".scroll").offset().left;
        var scrolliconMax = scrolliconMin + scrollWidth;
        $(".scrollicon").on("touchmove",function(event){
            var startX = event.originalEvent.changedTouches[0].pageX;
            if(startX < scrolliconMin){
                startX = scrolliconMin;
            }else if(startX > scrolliconMax){
                startX = scrolliconMax;
            }
            var left = startX - $(".scrollBox").offset().left - $(".scrollicon").width()*1/3;
            $(".scrollicon").css({"left":left,"position":"absolute","top":"18%"});
            //计算相当于第几年
            var year = parseInt((startX - scrolliconMin)/scrollWidth*99);
            year = year > 0 ? year : 1;
            $(".currentTime").val(year);
        });
    });
    //解绑滑动滚条效果
    $(".scrollicon").on("touchend",function(){
        $(".scrollicon").off("touchmove");
        $(".currentTime").change();
    });
    //加减号
    $(".reduce,.plus").on("click touch",function(){
        var current = parseInt($(".currentTime").val());
        if($(this).hasClass("reduce")){
            current--;
        }else{
            current++;
        }
        if(current > 0 && current < 100){
            $(".currentTime").val(current).change();
        }
    });
    //计算按钮
    var params = null;
    $("#calculation").on("click touch",function(){
        if($(this).hasClass("calculationDisabled1")){
            shareParams = "";
            $(this).removeClass("calculationDisabled1").text("计算");
            $(".check").prop("readonly",false);
            $(".dueTime,.additionalStartDueTime,.additionalEndDueTime").prop("disabled",false);
            $(".additionalBtn,.flat,.compound,.compare,.dayType,.monthType,.yearType,.deleteItem").removeClass("disabled");
            return false;
        }
        var principal = parseInt($("#principal").val());
       var num = $("#rate").val().trim();
       if(num.length == 0){
            $.dialog({
            	 contentHtml : '<p style="text-align: center;">年利率不能为空</p >'
            	});
        return;
       }
        var rate = parseFloat(num)/100;
        var dueTime = parseInt($("#dueTime").val());
        //var currentTime = parseInt($("#currentTime").val());
        var currentTime = dueTime;//默认期限为最长的本金投入日期
        var additional = [];
        $(".additionalItemError").removeClass("additionalItemError");
        $(".additionalItem").each(function(){
            var startTime = parseInt($(this).find(".additionalStartDueTime").val());
            var endTime = parseInt($(this).find(".additionalEndDueTime").val());
            var principal = parseInt($(this).find(".principal").val());
            currentTime = currentTime > endTime ? currentTime : endTime;
            if(startTime >= endTime || principal == 0 || isNaN(principal)){
                $(this).addClass("additionalItemError");
            }
            additional.push({"startTime":startTime,"endTime":endTime,"principal":principal});
        });
        //需求变更，默认第一年
        currentTime = 1;
        var topType = $(".topItem .actived").attr("type");
        var subType = $(".subItem .actived").attr("type");

        //保存参数，用于显示详细列表时使用
        params = {};
        params.principal = principal;
        params.rate = rate;
        params.dueTime = dueTime;
        params.additional = additional;
        params.topType = topType;
        params.subType = subType;
        params.currentTime = currentTime;
        $(".resultList .list-item-data").remove();
        $(".resultList").hide();
        $(".result").show();
        //初始化计算结果中的日期
        $(".currentTime").val(currentTime).change();
        
        //需求变更
        $(this).addClass("calculationDisabled1").text("返回修改");
        $(".check").prop("readonly",true);
        $(".dueTime,.additionalStartDueTime,.additionalEndDueTime").prop("disabled",true);
        $(".additionalBtn,.flat,.compound,.compare,.dayType,.monthType,.yearType,.deleteItem").addClass("disabled");
        //将子任务转换为字符串
        var additional01 = "";
        $.each(params.additional,function(i,obj){
            additional01 += "|"+obj.startTime+"-"+obj.endTime+"-"+obj.principal;
        });
        params.additional = additional01.substr(1);
        if(window.location.search == ""){
            shareParams = "?"+$.param(params);
        }else{
            shareParams = "&"+$.param(params);
        }
        params.additional = additional;
    });
    
    //展开详细列表
    $(".showDetails").on("click touch",function(){
        if(params.topType == '3' && $(".compareHeader").is(":hidden") || params.topType != '3' && $(".noCompareHeader").is(":hidden")){
            if($(".resultList .list-item-data").length == 0 && params != null){
                //进行计算
                var html = "";
                $(".compareHeader,.noCompareHeader").hide();
                //for(var i = 1;i <= params.currentTime;i++){   固定显示99年的数据
                for(var i = 1;i <= 99;i++){
                    if(params.topType == '1'){
                        //单利
                        var flat = flatInterest(params.principal ,params.rate ,params.dueTime ,i,params.additional);
                        //本金和     本息和   利息和
                        html += "<div class=\"list-item list-item-data\">"+
                                        "<div class=\"item01\">第"+i+"年</div>"+
                                        "<div class=\"item02\">"+flat['principalTotal']+"</div>"+
                                        "<div class=\"item03\">"+flat['interestTotal'].toFixed(2)+"</div>"+
                                        "<div class=\"item04\">"+flat['total'].toFixed(2)+"</div>"+
                                        "<div class=\"clearFixed\"></div>"+
                                "</div>";
                    }else if(params.topType == '2'){
                        //复利
                        var compound = compoundInterest(params.principal ,params.rate ,params.dueTime ,i ,params.subType ,params.additional);
                        //本金和     本息和   利息和
                        html += "<div class=\"list-item list-item-data\">"+
                                        "<div class=\"item01\">第"+i+"年</div>"+
                                        "<div class=\"item02\">"+compound['principalTotal']+"</div>"+
                                        "<div class=\"item03\">"+compound['interestTotal'].toFixed(2)+"</div>"+
                                        "<div class=\"item04\">"+compound['total'].toFixed(2)+"</div>"+
                                        "<div class=\"clearFixed\"></div>"+
                                "</div>";
                    }else{
                        var flat = flatInterest(params.principal ,params.rate ,params.dueTime ,i,params.additional);
                        var compound = compoundInterest(params.principal ,params.rate ,params.dueTime ,i ,params.subType ,params.additional);
                        //本金和     单利本息和   复利本息和
                        
                       var percent = flat['total'].toFixed(2)/compound['total'].toFixed(2);
                      var num = keepTwoDecimalFull(percent);
                        html += "<div class=\"list-item list-item-data\">"+
                                        "<div class=\"item01\">第"+i+"年</div>"+
                                        "<div class=\"item02\">"+compound['principalTotal']+"</div>"+
                                        "<div class=\"item03\">"+flat['total'].toFixed(2)+"</div>"+
                                        "<div class=\"item04\">"+compound['total'].toFixed(2)+"</div>"+
                                        "<div class=\"item05\">"+num+"</div>"+
                                        "<div class=\"clearFixed\"></div>"+
                                "</div>";
                    }
                }
                $(".list-item-after").before(html);
                if(params.topType == '3'){
                    $(".compareHeader").show(300);
                }else{
                    $(".noCompareHeader").show(300);
                }
            }else{
                if(params.topType == '3'){
                    $(".compareHeader").show(300);
                }else{
                    $(".noCompareHeader").show(300);
                }
            }
            //列表往上移一点
            setTimeout(function(){
                window.scrollTo(window.scrollX,window.scrollY+20);
            },300);
        }else{
            $(".resultList").hide(300);
        }
    });
    $(".container").on("blur",".check",function(){
        
    });
    //取整
    $(".container").on("blur",".getInt",function(){
        $(this).val(parseInt($(this).val()));
    });
    
    /*******初始化********/
    try{
        if(requestparams.principal != "" && requestparams.principal != "null"){
            $("#principal").val(requestparams.principal);
            $("#rate").val(parseFloat(requestparams.rate)*100);
            $("#dueTime").val(requestparams.dueTime);
            //利息计算方式
            $(".compare,.compound,.flat").each(function(){
                if(requestparams.topType == $(this).attr("type")){
                    $(this).click();
                }
            });
            //二级利息计算方式
            if(requestparams.topType != '1'){
                $(".dayType,.monthType,.yearType").each(function(){
                    if(requestparams.subType == $(this).attr("type")){
                        $(this).click();
                    }
                });
            }
            //子任务
            if(requestparams.additional != "" && requestparams.additional != "null"){
                var additional = requestparams.additional.split("|");
                $.each(additional,function(i,item){
                    item = item.split("-");
                    $(".additionalBtn").click();
                    $(".additional .additionalItem").last().find(".additionalStartDueTime").val(item[0]);
                    $(".additional .additionalItem").last().find(".additionalEndDueTime").val(item[1]);
                    $(".additional .additionalItem").last().find(".principal").val(item[2]);
                });
            }
            $("#calculation").click().hide();
        }
    }catch(error){
        
    }
})

function init(){
    var optionHtml = "";
    var optionHtml01 = "";
    var characters = ["十","一","二","三","四","五","六","七","八","九"];
    for(var i=1;i<100;i++){
        optionHtml += "<option value='"+i+"'>"+i+"</option>";
        optionHtml01 += "<option value='"+i+"'>第"+i+"年</option>";
//        if(i < 10){
//            optionHtml01 += "<option value='"+i+"'>第"+characters[i]+"年</option>";
//        }else if(i == 10){
//            optionHtml01 += "<option value='"+i+"'>第"+characters[0]+"年</option>";
//        }else{
//            var chars = i+"";
//            if(chars.substr(1,1) != "0"){
//                if(chars.substr(0,1) != "1"){
//                    optionHtml01 += "<option value='"+i+"'>第"+characters[chars.substr(0,1)]+characters[0]+characters[chars.substr(1,1)]+"年</option>";
//                }else{
//                    optionHtml01 += "<option value='"+i+"'>第"+characters[0]+characters[chars.substr(1,1)]+"年</option>";
//                }
//            }else{
//                optionHtml01 += "<option value='"+i+"'>第"+characters[chars.substr(0,1)]+characters[0]+"年</option>";
//            }
//        }
    }
    $(".dueTime").html(optionHtml);
    $(".currentTime").html(optionHtml01);
    
    //安卓时，当字号为单数时，line-height字体会导致偏上1px
    var userAgent = navigator.userAgent;
    if(userAgent.toLowerCase().indexOf("android") !== -1){
            $(".marginTop1").css("padding-top","1px");
            $(".marginTop2").css("padding-top","2px");
            $(".selectBox .selectIcon").css("top","46%");
    }
}
function keepTwoDecimalFull(num) {
  var result = parseFloat(num);
  if (isNaN(result)) {
    alert('传递参数错误，请检查！');
    return false;
  }
  result = Math.round(num * 100) / 100;
  var s_x = result.toString();
  var pos_decimal = s_x.indexOf('.');
  if (pos_decimal < 0) {
    pos_decimal = s_x.length;
    s_x += '.';
  }
  while (s_x.length <= pos_decimal + 2) {
    s_x += '0';
  }
  return s_x;
}

/**
 * 单利计算器（计算至某一期）
 * principal 本金， rate 年利率(0.5)，dueTime 期限，currentTime 当前期数（用于指定计算指定期数的本息和）
 * additional 追加任务，数组，包含对象，属性：startTime | endTime | principal，如[{},{},{}]
 * 金额单位均为 元，期数单位均为 年
 * */
function flatInterest(principal ,rate ,dueTime ,currentTime,additional){
    var ret = [];
    principal = parseInt(principal);
    rate = parseFloat(rate);
    dueTime = parseInt(dueTime);
    currentTime = parseInt(currentTime);
    
    if(isNaN(currentTime) || isNaN(principal) || isNaN(rate) || isNaN(dueTime)){
        return false;
    }
    //计算本期
    if(currentTime > dueTime){
        //当前期大于期限，则使用公式  totol = dueTime*principal + principal*rate*(currentTime+1/2-dueTime/2)
        ret['total'] = dueTime*principal + principal*rate*(currentTime+1/2-dueTime/2)*dueTime;
        ret['principalTotal'] = dueTime*principal;
    }else{
        //当前期小于等于期限，则使用公式  totol = currentTime*principal + principal*rate*(1+currentTime)*currentTime/2
        ret['total'] = currentTime*principal + principal*rate*(1+currentTime)*currentTime/2;
        ret['principalTotal'] = currentTime*principal;
    }
    //是否有追加任务
    if(additional !== undefined){
        //每个任务都按照单独的单利来计算
        if(typeof(additional) !== "object"){
            return false;
        }
        var additionalError = false;
        $.each(additional,function(index,item){
            var startTime = parseInt(item.startTime);
            if(currentTime >= startTime){
                //若当前期数大于等于开始追加的时间，则说明该追加任务已产生本息
                var additionalDueTime = parseInt(item.endTime) - startTime + 1;//该追加任务的期限
                var additionalCurrentTime = currentTime - startTime + 1;//该追加任务的当前期数
                var additionalRet = flatInterest(item.principal ,rate ,additionalDueTime ,additionalCurrentTime);
                if(additionalRet === false){
                    additionalError = true;
                }
                ret['total'] += additionalRet['total'];
                ret['principalTotal'] += additionalRet['principalTotal'];
            }
        });
        if(additionalError === true){
            return false;
        }
    }
    ret['interestTotal'] = ret['total'] - ret['principalTotal'];
    
    return ret;
}

/**
 * 复利计算器（计算至某一期）
 * principal 本金， rate 利率，dueTime 期限
 * currentTime 当前期数（用于指定计算指定期数的本息和），type 复利类型（1：按年复息，2：按月复息，3：按日复息）
 * additional 追加任务，数组，包含对象，属性：startTime | endTime | principal，如[{},{},{}]
 * 金额单位均为 元
 * */
function compoundInterest(principal ,rate ,dueTime ,currentTime ,type ,additional){
    var ret = [];
    principal = parseInt(principal);
    rate = parseFloat(rate);
    dueTime = parseInt(dueTime);
    currentTime = parseInt(currentTime);
    type = parseInt(type);
    
    if(isNaN(currentTime) || isNaN(principal) || isNaN(rate) || isNaN(dueTime) || isNaN(type)
            || (type != 1 && type != 2 && type != 3)){
        return false;
    }
    //计算本期
    if(currentTime > dueTime){
        //当前期大于期限
        ret['total'] = 0;
        var monthRate = rate/12;
        var dayRate = rate/365;
        for(var i=0;i < currentTime;i++){
            //从第二期开始，本期计算本息和的本金为上一期本息和+本期本金
            if(ret['total'] == 0){
                //第一期用本金
                ret['total'] = principal;
            }else if(i < dueTime){
                //在期限内，每期都有追加本金
                ret['total'] = ret['total'] + principal;
            }else{
                //期限外，本金不再追加
                ret['total'] = ret['total'];
            }
            if(type == 1){
                ret['total'] = ret['total']*rate + ret['total'];
            }else if(type == 2){
                for(var j=0;j<12;j++){
                    //按月计息（利滚利）
                    ret['total'] = ret['total']*monthRate + ret['total'];
                }
            }else{
                for(var j=0;j<365;j++){
                    //按日计息（利滚利）
                    ret['total'] = ret['total']*dayRate + ret['total'];
                }
            }
        }
        ret['principalTotal'] = dueTime*principal;
    }else{
        //当前期小于等于期限
        ret['total'] = 0;
        var monthRate = rate/12;
        var dayRate = rate/365;
        for(var i=0;i < currentTime;i++){
            //从第二期开始，本期计算本息和的本金为上一期本息和+本期本金
            ret['total'] = ret['total'] == 0 ? principal : ret['total'] + principal;
            if(type == 1){
                ret['total'] = ret['total']*rate + ret['total'];
            }else if(type == 2){
                for(var j=0;j<12;j++){
                    //按月计息（利滚利）
                    ret['total'] = ret['total']*monthRate + ret['total'];
                }
            }else{
                for(var j=0;j<365;j++){
                    //按日计息（利滚利）
                    ret['total'] = ret['total']*dayRate + ret['total'];
                }
            }
        }
        ret['principalTotal'] = currentTime*principal;
    }
    
    //是否有追加任务
    if(additional !== undefined){
        //每个任务都按照单独的单利来计算
        if(typeof(additional) !== "object"){
            return false;
        }
        var additionalError = false;
        $.each(additional,function(index,item){
            var startTime = parseInt(item.startTime);
            if(currentTime >= startTime){
                //若当前期数大于等于开始追加的时间，则说明该追加任务已产生本息
                var additionalDueTime = parseInt(item.endTime) - startTime + 1;//该追加任务的期限
                var additionalCurrentTime = currentTime - startTime + 1;//该追加任务的当前期数
                var additionalRet = compoundInterest(item.principal ,rate ,additionalDueTime ,additionalCurrentTime,type);
                if(additionalRet === false){
                    additionalError = true;
                }
                ret['total'] += additionalRet['total'];
                ret['principalTotal'] += additionalRet['principalTotal'];
            }
        });
        if(additionalError === true){
            return false;
        }
    }
    ret['interestTotal'] = ret['total'] - ret['principalTotal'];
    return ret;
}